using Services;
using UnityEngine;
using UnityEngine.UI;

public class InformationWindow : UI_Dynamic
{
    private EventSystem eventSystem;
    private Text m_text;
    private Vector2 position;
    private float offset;
    private GlobalGameCycle cycle;

    private void Start()
    {
        cycle = ServiceLocator.Get<GlobalGameCycle>();
        eventSystem = ServiceLocator.Get<EventSystem>();
        eventSystem.AddListener<string, Vector2, float>(EEvent.View, Show);
        eventSystem.AddListener(EEvent.EndView, Hide);
        m_text = GetComponentInChildren<Text>();
        eventSystem.AddListener<EGameState, EGameState>(EEvent.GameStateChange, OnGameStateChange);
    }

    private void Show(string infomation, Vector2 _position, float _offset)
    {
        immediate_next = true;
        Visible = false;
        if (string.IsNullOrEmpty(infomation))
            return;
        position = _position;
        offset = _offset;
        m_text.text = infomation;
        canvasGroup.interactable = true;
        cycle.AttachToGameCycle(EInvokeMode.NextUpdate, DelayMove);
    }

    private void DelayMove()
    {
        Width = rectTransform.rect.width / 800 * Screen.width;
        Height = rectTransform.rect.height / 450 * Screen.height;
        Move(position, offset);
        Visible = true;
        cycle.RemoveFromGameCycle(EInvokeMode.NextUpdate, DelayMove);
    }

    private void Hide()
    {
        Visible = false;
        cycle.RemoveFromGameCycle(EInvokeMode.NextUpdate, DelayMove);
    }

    private void OnGameStateChange(EGameState from, EGameState to)
    {
        Visible = false;
    }
}